package com.hymjweb.demo.hymj.master_bill_manage.flight.controller;

import com.alibaba.fastjson.JSONObject;
import com.hymjweb.demo.framework.result.BaseResultMap;
import com.hymjweb.demo.framework.sys.BaseController;
import com.hymjweb.demo.framework.sys.SysConstant;
import com.hymjweb.demo.framework.util.DataTypeUtil;
import com.hymjweb.demo.framework.util.DateUtil;
import com.hymjweb.demo.hymj.basic_data_manage.xt_airport.goods_site.bean.XtAirportGoodsSitePojo;
import com.hymjweb.demo.hymj.basic_data_manage.xt_airport.goods_site.service.XtAirportGoodsSiteService;
import com.hymjweb.demo.hymj.flight_manage.service.BFlightService;
import com.hymjweb.demo.hymj.master_bill_manage.flight.bean.BMasterBillFlightBean;
import com.hymjweb.demo.hymj.master_bill_manage.flight.bean.BMasterBillFlightPojo;
import com.hymjweb.demo.hymj.master_bill_manage.flight.service.BMasterBillFlightService;
import com.hymjweb.demo.hymj.master_bill_manage.load.bean.BNativeBillLoadPojo;
import com.hymjweb.demo.hymj.master_bill_manage.load.service.BNativeBillLoadService;
import com.hymjweb.demo.hymj.master_bill_manage.other_charges.bean.BMasterBillOtherChargePojo;
import com.hymjweb.demo.hymj.master_bill_manage.other_charges.service.BMasterBillOtherChargeService;
import com.hymjweb.demo.hymj.native_bill_manage.bean.BNativeBillPojo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Controller
@RequestMapping("/pages/master_bill_manage/flight")
public class BMasterBillFlightController extends BaseController {

    @Autowired
    private BMasterBillFlightService bMasterBillFlightService;

    @Autowired
    private BNativeBillLoadService bNativeBillLoadService;

    @Autowired
    private BFlightService bFlightService;

    @Autowired
    private BMasterBillOtherChargeService bMasterBillOtherChargeService;

    @Autowired
    private XtAirportGoodsSiteService xtAirportGoodsSiteService;

    @RequestMapping("/init")
    public String init() {
        return "pages/master_bill_manage/flight/bmasterbillflight";
    }

    /**
     * 初始货进入主单添加页面
     *
     * @return 主单添加页面地址
     */
    @RequestMapping("/createFlightMasterBill")
    public String createFlightMasterBill() {

        setRequestAttribute("openMasterBillDate", DateUtil.dateToStr_yyyy_MM_dd(DateUtil.getSysDate()));
        setRequestAttribute("openMasterBillDepartmentId", getLoginUserDepartment().getId());
        setRequestAttribute("openMasterBillUserId", getLoginUserId());
        setRequestAttribute("opType", SysConstant.OPER_ADD);

        return "pages/master_bill_manage/flight/createFlightMasterBill";
    }

    @RequestMapping("/getBMasterBillFlightPojoById")
    @ResponseBody
    public BMasterBillFlightPojo getBMasterBillFlightPojoById(String id) {
        return bMasterBillFlightService.getBMasterBillFlightPojoById(id);
    }

    /**
     * 查询主单列表
     *
     * @return 主单列表页面地址
     */
    @RequestMapping("/flightMasterBillList")
    public String nativeBillList() {
        return "pages/master_bill_manage/flight/flightMasterBillList";
    }

    /**
     * 根据查询条件查询主单列表
     *
     * @param param 查询参数
     * @return 返回查询列表对象
     * @throws Exception 抛出异常
     */
    @RequestMapping("/queryFlightMasterBill")
    @ResponseBody
    public Object queryFlightMasterBill(@RequestParam(required = true) Map param) {
        return bMasterBillFlightService.getPageList(param);
    }

    /**
     * 根据查询条件查询主单包含的分单
     *
     * @param param
     * @return
     * @throws Exception
     */
    @RequestMapping("/queryNativeBillList")
    @ResponseBody
    public Object queryNativeBillList(@RequestParam(required = true) Map param) {
        return bMasterBillFlightService.queryNativeBillList(param);
    }

    /**
     * 根据主单号获取主单配置的分单原始对象信息
     *
     * @param masterBillId
     * @return
     * @throws Exception
     */
    @RequestMapping("/queryBNativeBillPojoListByMasterBillId")
    @ResponseBody
    public Object queryBNativeBillPojoListByMasterBillId(String masterBillId) throws Exception {
        if (DataTypeUtil.isEmptyStr(masterBillId)) {
            throwException("空运主单查询包含原始配载分单参数错误");
        }

        List<BNativeBillPojo> bNativeBillPojoList = bMasterBillFlightService.queryBNativeBillPojoListByMasterBillId(masterBillId);

        BaseResultMap baseResultMap = new BaseResultMap();
        baseResultMap.setOk(true);
        baseResultMap.setData(bNativeBillPojoList);
        return baseResultMap;
    }

    @RequestMapping("/queryMasterBillFlightPojoById")
    @ResponseBody
    public Object queryMasterBillFlightPojoById(String masterBillId) throws Exception {
        if (DataTypeUtil.isEmptyStr(masterBillId)) {
            throwException("根据主单ID加载主单对象失败!");
        }

        BMasterBillFlightPojo flightPojo = bMasterBillFlightService.getBMasterBillFlightPojoById(masterBillId);

        if (flightPojo == null) {
            throwException("根据主单ID加载主单对象失败，主单对象可能被删除!");
        }

        BaseResultMap baseResultMap = new BaseResultMap();
        baseResultMap.setOk(true);
        baseResultMap.setData(flightPojo);

        return baseResultMap;
    }

    /**
     * 新添加主单
     *
     * @param jsonMasterBillPojo 新加主单对象
     * @return 添加结果对象
     */
    @RequestMapping("/addMasterFlightBill")
    @ResponseBody
    public Object addMasterFlightBill(@RequestBody(required = true) JSONObject jsonMasterBillPojo) throws Exception {

        if (jsonMasterBillPojo == null) {
            throwException("添加航空主单参数错误");
        }

        BaseResultMap baseResultMap = new BaseResultMap();
        baseResultMap.setOk(true);
        baseResultMap.setMessage("保存航空主单成功!");

        // json 对象转 Java 对象
        BMasterBillFlightBean bMasterBillFlightBean = bMasterBillFlightService.convertJSONObjToJavaObj(jsonMasterBillPojo);
        if (bMasterBillFlightBean == null) {
            throwException("添加航空主单对象转换失败!");
        }
        // 写入主单信息与主单配置的分单信息
        int effectRows = bMasterBillFlightService.addMasterFlightBill(bMasterBillFlightBean);

        if (effectRows == BMasterBillFlightService.MASTER_BILL_EXSIT) {
            baseResultMap.setOk(false);
            baseResultMap.setMessage("[" + bMasterBillFlightBean.getId() + "] 主单号已经在主单表中存在不能重复添加!");
        } else if (effectRows <= SysConstant.INT_ZERO) {
            baseResultMap.setOk(false);
            baseResultMap.setMessage("添加航空主单失败，请重试!");
        }

        return baseResultMap;
    }


    @RequestMapping("/showUpdateMasterBill")
    public String showUpdateBill(String opType, String id) throws Exception {

        if (DataTypeUtil.isEmptyStr(opType) || DataTypeUtil.isEmptyStr(id)) {
            throwException("获取航空主单对象参数错误!");
        }

        /**
         * 1.1  根据目的省加载目的市列表(前端处理)
         * 	1.2 加载航班号 (后端处理)
         * 	1.3  加载分单列表 (后端处理)
         * 	1.4 发货人列表 (前端处理)
         * 	1.5  收货人列表 (前端处理)
         */

        // 1.获取航空主单对象
        BMasterBillFlightPojo pojo = bMasterBillFlightService.getBMasterBillFlightPojoById(id);
        // 1.3 获取航空主单位包含的分单列表对象
        Map<String, Object> param1 = new HashMap<>();
        param1.put("masterBillId", pojo.getId());
        List<BNativeBillLoadPojo> bNativeBillLoadPojoList = bMasterBillFlightService.queryNativeBillListNoPage(param1);

        // 根据获取到的加载对象，再去取到分单对象，根据获取到的分前单对象，再更新其配置值，再进行返回前端
        List<BNativeBillPojo> loadBNativeBillPojoList = bNativeBillLoadService.getLoadBNativeBillPojoByLoadList(bNativeBillLoadPojoList);
        // 清空分单的说明信息，防止有特殊字符信息存在，造成转成 json 列表时出错
        if (loadBNativeBillPojoList != null && !loadBNativeBillPojoList.isEmpty()) {
            for (BNativeBillPojo billPojo : loadBNativeBillPojoList) {
                billPojo.setComment("");
            }
        }

        // 3.获取航空主单位包含的其他费用列表对象
        List<BMasterBillOtherChargePojo> bMasterBillOtherChargePojos = bMasterBillOtherChargeService.queryListByMasterBillId(pojo.getId());

        // 1.2 加载航班下拉列表
        Map<String, Object> param2 = new HashMap<>();
        param2.put("cityId", pojo.getDestCityId());
        param2.put("airportId", pojo.getAirportId());
        param2.put("airlinesId", pojo.getAirlinesId());
        param2.put("flightDate", DateUtil.dateToStr_yyyy_MM_dd(pojo.getFlightDate()));
        List<Map<String, Object>> bFlightList = bFlightService.queryFlightNoListByDropCnd(param2);

        // 加载货站列表
        /**
         *  airportId:airPortIdValue,
         *  airlinesId:airlinesIdValue,
         *  calcWeightCategoryId:calcWeightCategoryIdValue
         */
        Map<String, Object> param3 = new HashMap<>();
        param3.put("airportId", pojo.getAirportId());
        param3.put("airlinesId", pojo.getAirlinesId());
        param3.put("calcWeightCategoryId", pojo.getCalcWeightCategoryId());
        List<XtAirportGoodsSitePojo> goodsSiteList = xtAirportGoodsSiteService.queryNoPage(param3);

        // 主单对象
        setRequestAttribute("pojo", objectToJSONObject(pojo));
        // 主单包含的已配载的分单对象
        setRequestAttribute("loadBNativeBillPojoList", objectToJSONObject(loadBNativeBillPojoList));
        // 主单包含的其也费用对象
        setRequestAttribute("pojoOtherChargeList", objectToJSONObject(bMasterBillOtherChargePojos));

        // 主单航班下拉列表对象
        setRequestAttribute("bFlightList", objectToJSONObject(bFlightList));

        // 货站下拉列表
        setRequestAttribute("goodsSiteList", objectToJSONObject(goodsSiteList));

        // 设定操作类型为update
        setRequestAttribute("opType", opType);

        return "pages/master_bill_manage/flight/createFlightMasterBill";
    }

    /**
     * 更新主单
     *
     * @param jsonMasterBillPojo 需要更新的主单对象
     * @return 更新主单结果对象
     */
    @RequestMapping("/updateMasterFlightBill")
    @ResponseBody
    public Object updateMasterFlightBill(@RequestBody(required = true) JSONObject jsonMasterBillPojo) throws Exception {

        if (jsonMasterBillPojo == null) {
            throwException("更新航空主单参数错误!");
        }

        // json 对象转 Java 对象
        BMasterBillFlightBean bMasterBillFlightBean = bMasterBillFlightService.convertJSONObjToJavaObj(jsonMasterBillPojo);
        if (bMasterBillFlightBean == null) {
            throwException("更新航空主单对象转换失败!");
        }
        // 写入主单信息与主单配置的分单信息
        int effectRows = bMasterBillFlightService.updateMasterFlightBill(bMasterBillFlightBean);

        BaseResultMap baseResultMap = new BaseResultMap();
        baseResultMap.setOk(true);
        baseResultMap.setMessage("更新航空主单成功!");

        if (effectRows == BMasterBillFlightService.OP_FAIL) {
            baseResultMap.setOk(false);
            baseResultMap.setMessage("更新航空主单失败!");
        }

        return baseResultMap;
    }

    /**
     * 主单删除，参数形式为 id1,id2,id3
     *
     * @param param
     * @return
     */
    @RequestMapping("/deleteMasterBillByMasterBillIds")
    @ResponseBody
    public Object deleteMasterBillByMasterBillIds(@RequestBody(required = true) Map param) throws Exception {
        if (param == null || param.isEmpty()) {
            throwException("航空主单删除参数错误!");
        }

        int affectRows = bMasterBillFlightService.deleteMasterBillByMasterBillIds(param);

        BaseResultMap baseResultMap = new BaseResultMap();
        baseResultMap.setOk(true);
        baseResultMap.setMessage("航空主单删除成功!");

        if (affectRows <= SysConstant.INT_ZERO) {
            baseResultMap.setOk(false);
            baseResultMap.setMessage("航空主单删除失败!");
        }
        return baseResultMap;
    }


    /**
     * 无拉货状态航空主单删除
     * @param param
     * @return
     * @throws Exception
     */
    @RequestMapping("/noPullStatusCheckDeleteMasterBillByMasterBillIds")
    @ResponseBody
    public Object noPullStatusCheckDeleteMasterBillByMasterBillIds(@RequestBody(required = true) Map param) throws Exception {
        if (param == null || param.isEmpty()) {
            throwException("航空主单无拉货状态检测删除参数错误!");
        }

        int affectRows = bMasterBillFlightService.noPullStatusCheckDeleteMasterBillByMasterBillIds(param);

        BaseResultMap baseResultMap = new BaseResultMap();
        baseResultMap.setOk(true);
        baseResultMap.setMessage("航空主单无拉货状态检测删除成功!");

        if (affectRows <= SysConstant.INT_ZERO) {
            baseResultMap.setOk(false);
            baseResultMap.setMessage("航空主单无拉货状态检测删除失败!");
        }
        return baseResultMap;
    }




    /**
     * 主单对账状态修改
     *
     * @param param
     * @return
     * @throws Exception
     */
    @RequestMapping("/changeAccountCheckStatus")
    @ResponseBody
    public Object changeAccountCheckStatus(@RequestBody(required = true) Map param) throws Exception {

        if (param == null || param.size() == 0) {
            throwException("航空主单对账操作参数错误!");
        }

        // {billIds:canAccountCheckIds,accountCheckStatusId:accountStatus}
        int affectRows = bMasterBillFlightService.changeAccountCheckStatus(param);

        BaseResultMap baseResultMap = new BaseResultMap();
        baseResultMap.setOk(true);
        baseResultMap.setMessage("航空主单对账操作成功!");

        if (affectRows <= SysConstant.INT_ZERO) {
            baseResultMap.setOk(false);
            baseResultMap.setMessage("航空主单对账操作失败!");
        }
        return baseResultMap;
    }


    /**
     * 主单对账状态修改根据对账类型
     *
     * @param param
     * @return
     * @throws Exception
     */
    @RequestMapping("/changeAccountCheckStatusByAccountType")
    @ResponseBody
    public Object changeAccountCheckStatusByAccountType(@RequestBody(required = true) Map param) throws Exception {

        if (param == null || param.size() == 0) {
            throwException("航空主单对账操作参数错误!");
        }

        //{billIds:canAccountCheckIds,accountCheckStatusId:accountStatus,accountTypeId:accountType}
        int affectRows = bMasterBillFlightService.changeAccountCheckStatusByAccountType(param);

        Long accountTypeId = DataTypeUtil.toLongObject(param.get("accountTypeId"));
        /**
         * 主单运费、地面操作费、航空附加费、其他费用对账
         * accountType:
         * 0:航空运费
         * 1:地面操作费
         * 2:航空附加费
         * 3:其他费用
         */
        String title="";
        if(accountTypeId.longValue() == 0L){
            title = "航空运费";
        }
        else if(accountTypeId.longValue() == 1L){
            title = "地面操作费";
        }
        else if(accountTypeId.longValue() == 2L){
            title = "航空附加费";
        }
        else{
            title = "其他费用";
        }

        BaseResultMap baseResultMap = new BaseResultMap();
        baseResultMap.setOk(true);
        baseResultMap.setMessage("航空主单" + title + "对账操作成功!");

        if (affectRows <= SysConstant.INT_ZERO) {
            baseResultMap.setOk(false);
            baseResultMap.setMessage("航空主单" + title + "对账操作失败!");
        }
        return baseResultMap;
    }





    /**
     * 航空主单导入对账处理
     * @param accountFileType
     * @param upLoadFileData
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/accountFileUploadAndCheck", method = RequestMethod.POST)
    @ResponseBody
    public Object accountFileUploadAndCheck(Long accountFileType, MultipartFile upLoadFileData) throws Exception {

        if (upLoadFileData == null || accountFileType == null) {
            throwException("对账文件上传参数错误！");
        }

        String resultMsg = bMasterBillFlightService.accountFileUploadAndCheck(upLoadFileData,accountFileType);

        BaseResultMap baseResultMap = new BaseResultMap();
        baseResultMap.setOk(true);
        baseResultMap.setMessage(resultMsg.length()==0?"对账成功!":resultMsg);

        return baseResultMap;
    }



    /**
     * 航空主单结算处理
     * @param settlementFileType
     * @param upLoadFileData
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/settlementFileUploadAndCheck", method = RequestMethod.POST)
    @ResponseBody
    public Object settlementFileUploadAndCheck(Long settlementFileType, MultipartFile upLoadFileData) throws Exception {

        if (upLoadFileData == null || settlementFileType == null) {
            throwException("结算文件上传参数错误！");
        }

        String resultMsg = bMasterBillFlightService.settlementFileUploadAndCheck(upLoadFileData,settlementFileType);

        BaseResultMap baseResultMap = new BaseResultMap();
        baseResultMap.setOk(true);
        baseResultMap.setMessage(resultMsg.length()==0?"结算成功!":resultMsg);

        return baseResultMap;
    }

}
